package com.atguigu.gmall.realtime.util;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.annotation.NotSink;
import com.atguigu.gmall.realtime.bean.TableProcess;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.sink.PhoenixSink;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.shaded.guava18.com.google.common.base.CaseFormat;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * @Author lzc
 * @Date 2023/2/11 09:14
 */
public class FlinkSinUtil {
    
    public static SinkFunction<Tuple2<JSONObject, TableProcess>> getPhoenixSink() {
        return new PhoenixSink();
    }
    
    public static SinkFunction<String> getKafkaSink(String topic) {
        
        Properties props = new Properties();
        props.put("bootstrap.servers", Constant.KAFKA_BROKERS);
        props.put("transaction.timeout.ms", 15 * 60 * 1000);
        
        return new FlinkKafkaProducer<String>(
            "default",
            new KafkaSerializationSchema<String>() {
                @Override
                public ProducerRecord<byte[], byte[]> serialize(String element,
                                                                @Nullable Long timestamp) {
                    return new ProducerRecord<>(topic, element.getBytes(StandardCharsets.UTF_8));
                }
            },
            props,
            FlinkKafkaProducer.Semantic.EXACTLY_ONCE
        );
    }
    
    public static SinkFunction<Tuple2<JSONObject, TableProcess>> getKafkaSink() {
        Properties props = new Properties();
        props.put("bootstrap.servers", Constant.KAFKA_BROKERS);
        props.put("transaction.timeout.ms", 15 * 60 * 1000);
        return new FlinkKafkaProducer<Tuple2<JSONObject, TableProcess>>(
            "default",
            new KafkaSerializationSchema<Tuple2<JSONObject, TableProcess>>() {
                @Override
                public ProducerRecord<byte[], byte[]> serialize(Tuple2<JSONObject, TableProcess> t,
                                                                @Nullable Long timestamp) {
                    String topic = t.f1.getSinkTable();
                    JSONObject data = t.f0;
                    
                    return new ProducerRecord<>(topic, data.toJSONString().getBytes(StandardCharsets.UTF_8));
                }
            },
            props,
            FlinkKafkaProducer.Semantic.EXACTLY_ONCE
        );
    }
    
    // TODO
    public static <T> SinkFunction<T> getClickHouseSink(String table,
                                                        Class<T> tClass) {
        Field[] fields = tClass.getDeclaredFields();
        String columns = Arrays.stream(fields)
            .filter(f -> {
                NotSink notSink = f.getAnnotation(NotSink.class);
                return notSink == null;
            })
            .map(f -> CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, f.getName()))
            .collect(Collectors.joining(","));
        
        // insert into user(a,b,c)values(?,?,?)
        StringBuilder insertSql = new StringBuilder();
        insertSql
            .append("insert into ")
            .append(table)
            .append("(")
            .append(columns)  // 拼接字段名
            .append(")values(")
            .append(columns.replaceAll("[^,]+", "?")) // 拼接占位符
            .append(")");
        
        System.out.println("clickhouse的插入语句: " + insertSql);
        
        // 可以使用 jdbc sink
        return JdbcSink.sink(
            insertSql.toString(),
            new JdbcStatementBuilder<T>() {
                @Override
                public void accept(PreparedStatement ps,
                                   T t) throws SQLException {
                    //获取 class: 3种
                    // 1. Class.forName("") 2. 类名.class 3. 对象.getClass
                    // 负责给sql 中的占位符进行赋值  // TODO
                    // insert into a(stt,edt,keyword,keyword_count,ts)values(?,?,?,?,?)
                    Field[] fields = t.getClass().getDeclaredFields();
                    try {
                        for (int i = 0, position = 1; i < fields.length; i++) {
                            Field field = fields[i];
                            if (field.getAnnotation(NotSink.class) == null) {
                                field.setAccessible(true);
                                ps.setObject(position++, field.get(t));
                            }
                        }
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            },
            new JdbcExecutionOptions.Builder()
                .withBatchSize(100 * 10000)
                .withBatchIntervalMs(5000)
                .withMaxRetries(3)
                .build(),
            new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                .withDriverName(Constant.CLICKHOUSE_DRIVER)
                .withUrl(Constant.CLICKHOUSE_URL)
                .withUsername("default")
                .withPassword("aaaaaa")
                .build()
        );
    }
}
